package leetcode_jz_offer.day6_bin_tree;

import java.util.*;

/**
 * @author 美女
 * @date 2022/07/10 12:35
 **/
public class Num32III_从上到下打印二叉树 {
    private class TreeNode {
      int val;
      TreeNode left;
      TreeNode right;
      TreeNode(int x) { val = x; }
  }
    public List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> ret=new LinkedList<>();
        if(root==null){
            return ret;
        }
        Queue<TreeNode> queue=new ArrayDeque<>();
        Boolean flag=true;
        queue.offer(root);
        while(!queue.isEmpty()){
            Deque<Integer> temp=new LinkedList<>();
            int size=queue.size();
            //当前行元素插入temp中
            for(int i=0;i<size;i++){
                TreeNode cur= queue.poll();//顺序取出的
                //判断flag，搞清楚插入方向
                if(flag){//为true是左->右加入数组
                    temp.offerLast(cur.val);
                }else {
                    temp.offerFirst(cur.val);
                }
                if(cur.left!=null){
                    queue.offer(cur.left);
                }
                if(cur.right!=null){
                    queue.offer(cur.right);
                }
            }
            ret.add(new LinkedList<>(temp));
            flag=!flag;
        }
        return ret;
    }
}
